



import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from '../../utils/asyncWx.js';

import { request } from "../../request/index.js"

// pages/pay/pay.js
Page({
  data: {
    //收货地址
    address: {},
    //购物车信息
    cart: [],
    //总价
    totalPrice: 0,
    // 总数量
    totalNum: 0
  },
  onShow() {
    //获取收货地址
    const address = wx.getStorageSync("address");
    //获取缓存购物车信息
    let cart = wx.getStorageSync("cart") || []
    //过滤选中的购物车数组
    cart = cart.filter((v => v.checked))

    //更新数据
    //总价格 总数量
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price
      totalNum += v.num
    });
    //总集数
    this.setData({
      cart,
      address,
      totalPrice,
      totalNum
    })
  },
  //支付
  async handleOrderPay() {
    try {
      const token = wx.getStorageSync("token");
      //没有token就转跳取授权
      if (!token) {
        wx.navigateTo({ url: '/pages/auth/auth' });
        return;
      }
      //获取完毕创建订单
      //请求头参数 这步被封装到请求js里了
      // const header = { Authorization: token }
      //请求参数
      //总价格
      const order_price = this.data.totalPrice
      //收货地址
      const consignee_addr = this.data.address.all
      //订单数组
      let goods = []
      this.data.cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods }
      //发送请求创建订单 获取订单编号
      const res = await request({ url: "my/orders/create", method: "post", data: orderParams })
      // const order_number = res.data.message.order_number
      const order_number = "HMDD20190809000000001058"
      //发起预支付接口
      const { pay } = await request({ url: "/my/orders/req_unifiedorder", method: "post", data: { order_number } })
      //发起微信支付
      // await requestPayment({ timeStamp: '1565346079', nonceStr: 'U6tYjNdYvm3ReKgI', package: 'wx09182118356902a15c8b8d071931343000', signType: 'MD5', paySign: 'C514E29387794F84004C983AFFF4707F' })
      //查询后台订单
      const res3 = await request({ url: "/my/orders/chkOrder", method: "post", data: { order_number } })
      console.log(res3.data.meta.msg)
      await showToast({ title: "没有企业微信所以模拟支付成功！" })

      //在跳转之前 把已经购买的从缓存中删除
      let newCart = wx.getStorageSync("cart"); //上面已经拿过缓存但是被筛选过了 里面只有购物车页面选中的商品
      newCart = newCart.filter(v => !v.checked) //留下未被选中的
      wx.setStorageSync("cart", newCart);
      //支付成功跳转到订单页面
      wx.navigateTo({ url: '/pages/order/order', });

    } catch (error) {
      await showToast({ title: error })
    }

  }

})


